using System;
using System.ComponentModel;
using System.ComponentModel.Design;
using System.Collections;
using System.Drawing;
using System.Workflow.ComponentModel;
using System.Workflow.ComponentModel.Design;
using System.Workflow.ComponentModel.Compiler;
using System.Workflow.ComponentModel.Serialization;
using System.Workflow.Runtime;
using System.Workflow.Activities;
using System.Workflow.Activities.Rules;
using Decav.Gatsb.Mobile;
using Decav.Reality;
using Decav.Gatsb.Configuration;
using Decav.Security;
using System.IO;
using Decav.Gatsb.Application.Configuration;

namespace Decav.Gatsb.Application.CommandWorkflow
{
    /// <summary>
    /// Creates a new user and sends them their temporary email address and password
    /// </summary>
	public partial class CreateUserActivity : SequenceActivity
	{
		public CreateUserActivity()
		{
			InitializeComponent();
		}

        /// <summary>
        /// The dependency property that gets or sets the MobileMessage that will be posted to Gatsb.
        /// </summary>
        public static DependencyProperty InputMessageProperty = DependencyProperty.Register(
            "InputMessage", typeof(MobileMessage), typeof(CreateUserActivity));

        /// <summary>
        /// Gets or sets the MobileMessage that will be posted to Gatsb.
        /// </summary>
        [ValidationOption(ValidationOption.Required)]
        public MobileMessage InputMessage
        {
            get { return (MobileMessage)GetValue(InputMessageProperty); }
            set { SetValue(InputMessageProperty, value); }
        }

        /// <summary>
        /// The dependency property that gets or sets the users new password.
        /// </summary>
        public static DependencyProperty NewPasswordProperty = DependencyProperty.Register(
            "NewPassword", typeof(string), typeof(CreateUserActivity));

        /// <summary>
        /// Gets or sets the users new password.
        /// </summary>
        public string NewPassword
        {
            get { return (string)GetValue(NewPasswordProperty); }
            set { SetValue(NewPasswordProperty, value); }
        }
        

        private void createNewTempUser_ExecuteCode(object sender, EventArgs e)
        {
            string telNum = InputMessage.SendingAddress.ToString().Split('@')[0];
            bool telNumValid = PhoneNumber.IsValid(telNum);

            User usr = User.CreateNewUser(
                InputMessage.SendingAddress,
                new PhoneNumber(telNum),
                GetServiceProvider(InputMessage.SendingAddress));
            usr.PostalCode = "10002";

            if (!telNumValid)
                usr.AlternateSmsAddress = InputMessage.SendingAddress;

            NewPassword = UserValidationCode.Generate().ToString().ToUpper();
            GatsbServiceApplication.Current.CreateNewTemporaryUser(usr, HashedPassword.HashPassword(NewPassword));

            ConfigureMessages();
        }

        private void ConfigureMessages()
        {
            sendWelcome.MessageBody =
                string.Format("Welcome to Gatsb! Your account has been created. You need to login @ gatsb.com with:\r\nUser: {0}\r\nPwd: {1}",
                InputMessage.SendingAddress, NewPassword);
            sendHelp.MessageBody = File.ReadAllText(GatsbApplicationConfigurationSection.Current.HelpTextPath);
            sendHelp.SendingAddress = sendWelcome.SendingAddress = GatsbConfigurationSection.Current.NotificationFromAddress;
        }

        private TelephoneServiceProvider GetServiceProvider(EmailAddress address)
        {
            foreach (MobileProviderConfiguration config in GatsbConfigurationSection.Current.MobileProviders)
            {
                TelephoneServiceProvider provider = TelephoneServiceProvider.GetProvider(config.Type);
                if (provider.IsProviderMailAddress(address.ToString()))
                    return provider;
            }

            throw new AuthenticationException("The email address specified for the SMS cannot be parsed with the current TelephonServiceProvider's");
        }
	}
}
